'use strict';
const { Service } = require('egg');
const pinyin = require('pinyin');
const Result = require('../util/result');

class StationService extends Service {
  async create(data) {
    data.station_num = pinyin(data.station_name, {
      style: pinyin.STYLE_NORMAL,
    }).join('');
    try {
      const info = await this.ctx.model.Station.create({ ...data });
      return Result.success(info);
    } catch (error) {
      return Result.result(-1, '失败', error.name);
    }
  }

  async getAllStation(count) {
    const counts = count || 10;
    const info = await this.ctx.model.Station.findAndCountAll({ limit: counts });
    return Result.success(info);
  }

  async updateStation(id, data) {
    data.station_num = pinyin(data.station_name, {
      style: pinyin.STYLE_NORMAL,
    }).join('');
    const res = await this.findById(id);
    if (!res) return Result.warn(-1, 'id不存在');
    const info = await this.ctx.model.Station.update({ ...data }, {
      where: {
        id,
      },
    });
    if (info[0] <= 0) return Result.fail();
    const final_data = this.findById(id);
    return Result.success(final_data);
  }

  async deleteStation(id) {
    const info = await this.ctx.model.Station.destroy({
      where: {
        id,
      },
    });

    if (info[0] <= 0) return Result.fail();
    return Result.noDataSuccess();
  }

  async findById(id) {
    const info = await this.ctx.model.Station.findByPk(id);
    return Result.success(info);
  }

  async findByStationNum(num) {
    const info = await this.ctx.model.Station.findOne({
      where: { station_num: num },
    });
    return info;
  }
}
module.exports = StationService;
